<template>
  <div v-if="store.surveyCount">
    <draggable @start="draggStart" :ref="(el) => (componentRefs[index] = el)" v-model="store.coms" item-key="index">
      <template #item="{ element, index }">
        <div
          class="mb-10"
          :class="{
            active: store.currentComponentIndex === index,
          }"
          :key="element.id"
          @click="clickHandler(index)"
          v-show="isSurveyComName(element.name)"
        >
          <div class="item">{{ serialNum[index] }}、{{ substringText(element.status.title.status) }}</div>
        </div>
      </template>
    </draggable>
  </div>
  <div v-else>请添加题目</div>
</template>

<script setup>
import { computed, ref} from 'vue';
import draggable from 'vuedraggable';
import { useEditorStore } from '@/stores/useEditor';
import { isSurveyComName } from '@/utils';
// 组合式函数
import { useSurveyNo } from '@/hooks/useSurveyNo';
import EventBus from '@/utils/eventBus';
const store = useEditorStore();

const componentRefs = ref([]);

// 获取题目编号
const serialNum = computed(() => useSurveyNo(store.coms).value);

const draggStart = () => {
  store.setCurrentComponentIndex(-1);
};

const substringText = (text) => {
  return text.length > 10 ? text.substring(0, 10) + '...' : text;
};

const clickHandler = (index) => {
  if (store.currentComponentIndex === index) {
    store.setCurrentComponentIndex(-1);
  } else {
    store.setCurrentComponentIndex(index);
    EventBus.emit('scrollToCenter', index);
  }
};
</script>

<style scoped>
.item {
  color: var(--font-color-light);
  font-size: var(--font-size-base);
  padding: 10px;
  cursor: pointer;
}
.tip {
  height: calc(100% - 50px);
}
.active {
  transform: scale(1.04);
  transition: 0.5s;
  background-color: var(--border-color);
  border-radius: var(--border-radius-lg);
}
</style>
